import type OpenAI from "openai";
import type { UploadUserFile } from "element-plus";
import type { ChatHistoryWin, ModuleList } from "@/types";
import { useChatDataStore } from "@/store";
import {
  useChatScroll,
  useChatSession,
  useChatRegenerate,
  useChatControls,
  useAIStream,
} from "@/hooks";

export const useGeneralDataStore = defineStore("GeneralData", () => {
  const chatDataStore = useChatDataStore();

  // 重新生成的聊天记录
  const regenerateHistoryChat = ref<Map<number, ChatHistoryWin[]>>(new Map());
  // openai实例
  const openai = ref<OpenAI | null>(null);
  // 是否重新生成
  const isRegenerate = ref(false);
  // 模块列表
  const moduleList = ref<ModuleList>();
  // 上传文件列表
  const uploadFileList = ref<UploadUserFile[]>([]);
  // 代码块工具栏是否吸附
  const isSticky = ref(false);
  // 选择模型功能
  const selectAIFunction = ref<Record<string, boolean>>({
    selected_R1: false,
    internetSearch: false,
  });
  // 控制代码编辑器显示/隐藏的状态
  const showCodeEditor = ref(false);
  // 代码信息配置
  const codeInfoConfig = reactive({
    code: "",
    language: "",
    codeBlockId: "",
  });

  // 组合hooks
  const { sessionBottomRef, scrollToBottom } = useChatScroll();
  const { chatInput, textareaRef, newSession } = useChatSession();
  const { regenerateChatNewIndex, toggleAssistantHistoryChat } =
    useChatRegenerate();
  const { isPause, isRequestLoading, isGenerating, pauseGeneration } =
    useChatControls();
  const { abortController, handleAIStream } = useAIStream();

  // 发送新消息
  const send = async (model = false) => {
    if (!chatInput.value.trim() || !openai.value) return;
    if (abortController.value) return;

    const userMessage = chatInput.value;
    chatInput.value = "";

    // 添加用户消息
    chatDataStore.chatHistoryWin.push({
      role: "user",
      content: userMessage,
      id: Date.now().toString() + Math.random().toString(36).slice(2),
    });
    nextTick(() => scrollToBottom());

    // 检查是否已有会话
    const isExistingChat = chatDataStore.categorizedChats.some((category) =>
      category.thisChats.some((chat) => chat.id === chatDataStore.currentChatId)
    );

    if (!isExistingChat) {
      chatDataStore.addNewChatHistory(`对话 ${new Date().toLocaleString()}`);
    }

    // 添加助手消息占位
    const assistantIndex = chatDataStore.chatHistoryWin.length;
    chatDataStore.chatHistoryWin.push({
      role: "assistant",
      content: "",
      id: Date.now().toString(),
      isLoading: true,
      isGenerating: true,
    });

    await handleAIStream({
      messages: chatDataStore.chatHistoryWin.slice(0, -1),
      openai: openai.value as OpenAI,
      targetIndex: assistantIndex,
      model: model ? "deepseek-reasoner" : "deepseek-chat",
    });
  };

  // 重新生成
  const regenerate = async (index: number) => {
    isPause.value = false;
    const oldData = { ...chatDataStore.chatHistoryWin[index] };

    await handleAIStream({
      messages: chatDataStore.chatHistoryWin.slice(0, index),
      openai: openai.value as OpenAI,
      targetIndex: index,
      isRegenerate: true,
      oldData: oldData,
    });
  };

  // 编辑并重新发送
  const editAndResend = async (content: string, index: number) => {
    if (abortController.value) return;
    isPause.value = false;

    chatDataStore.chatHistoryWin[index] = {
      role: "user",
      content,
    };

    await handleAIStream({
      messages: chatDataStore.chatHistoryWin.slice(0, index + 1),
      openai: openai.value as OpenAI,
      targetIndex: index + 1,
    });
  };

  // 打开代码编辑器
  const openRunOrEditCode = (newCode: string, language: string, codeBlockId: string) => {
    showCodeEditor.value = true;
    codeInfoConfig.code = newCode;
    codeInfoConfig.language = language;
    codeInfoConfig.codeBlockId = codeBlockId;
  };
  return {
    chatInput,
    openai,
    isPause,
    isRegenerate,
    isRequestLoading,
    isGenerating,
    isSticky,
    sessionBottomRef,
    textareaRef,
    moduleList,
    regenerateHistoryChat,
    uploadFileList,
    selectAIFunction,
    regenerateChatNewIndex,
    showCodeEditor,
    codeInfoConfig,
    send,
    regenerate,
    editAndResend,
    scrollToBottom,
    newSession,
    useAIStream,
    pauseGeneration,
    toggleAssistantHistoryChat,
    openRunOrEditCode,
  };
});
